package com.geh.learn.util;

import com.geh.learn.bean.Student;

import java.util.HashMap;
import java.util.Map;

/**
 * Map中的元素输出是无序的
 *
 * Created by gehui on 2017/2/23.
 */
public class HashMapLearn {
    public static void main(String[] args) {
        // HashMap初始化
        Map<String, String> map1 = new HashMap<String, String>() {
            {
                // 可以一行一行的
                put("key1", "value1");
                put("key2", "value2");
                put("key3", "value3");
                put("key4", "value4");
                //
                for (int i = 0; i < 1000000; i++) {
                    put(String.valueOf(i), "hello " + i);
                }
            }
        };

        // 使用keyset来遍历，需要多取一步，效率会低一些
        for (String key : map1.keySet()) {
            String value = map1.get(key);
        }

        // 直接使用EntrySet访问，可以提高一下效率
        for (Map.Entry<String, String> entry : map1.entrySet()) {
            String value = entry.getValue();
        }

        // 验证HashMap中使用的是（equals or hashCode）
        Student s1 = new Student("001", "Mike", 82);
        Student s2 = new Student("001", "Joe", 73);
        Student s3 = new Student("003", "Lily", 99);
        Map<Student, String> tm = new HashMap<>();
        tm.put(s1, "s1");
        tm.put(s2, "s2");
        tm.put(s3, "s3");
        for (Map.Entry<Student, String> entry : tm.entrySet()) {
            System.out.println(entry.getValue());
            System.out.println(entry.getKey());
        }
    }
}
